﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using RAP.Framework.Libary.JSONSocket;
using RAP.Framework.Libary.Utils;

namespace RAP.Developer.Tools.DebugConsole
{
  /// <summary>
  /// 远程监视客户端
  /// </summary>
  public class RemoteDebugClient
  {
    private SocketJSON _socketJSON = null;

    public EventHandler<DebugLogData> OnLogArrived;

    private bool _enable = true;
    private bool _isConnecting = false;

    public void ConnectServer()
    {
      if (_isConnecting)
      {
        return;
      }
      Stop();
      _enable = true;
      _isConnecting = true;
      _socketJSON = new SocketJSON();
      _socketJSON.ServerIP = ConfigurationManager.AppSettings.ToString("serverIP", "127.0.0.1");
      _socketJSON.Port = ConfigurationManager.AppSettings.ToInt32("port", 9001);
      _socketJSON.OnError += OnError;
      _socketJSON.OnDataArrived += OnDataArrived;
      Task.Run(() =>
      {
        while (_enable)
        {
          WriteLog($"正在连接【RAP】Web服务端({_socketJSON.ServerIP}:{_socketJSON.Port})...", ConsoleColor.Green);
          if (_socketJSON.Connect())
          {
            if (_enable)
            {
              WriteLog("连接成功！", ConsoleColor.Green);
            }
            else
            {
              OnError("连接请求已终止！");
            }
            break;
          }
          else
          {
            OnError("连接失败！");
            Thread.Sleep(1000);
          }
        }
        _isConnecting = false;
      });

    }

    /// <summary>
    /// 停止
    /// </summary>
    public void Stop()
    {
      _enable = false;
      if (_socketJSON != null)
      {
        try
        {
          _socketJSON.Dispose();
          _socketJSON.OnError -= OnError;
          _socketJSON.OnDataArrived -= OnDataArrived;
          _socketJSON = null;
          OnError("连接已断开！");
        }
        catch (Exception ex)
        {
          OnError(ex);
        }
      }
      _isConnecting = false;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="logMsg"></param>
    private void WriteLog(string logMsg, ConsoleColor foreColor = ConsoleColor.White, ConsoleColor bgColor = ConsoleColor.Black)
    {
      this.OnLogArrived?.Invoke(this, new DebugLogData
      {
        Msg = logMsg,
        ForegroundColor = foreColor,
        BackgroundColor = bgColor
      });
    }

    /// <summary>
    /// 触发错误消息到UI界面
    /// </summary>
    /// <param name="exc"></param>
    private void OnError(Exception exc)
    {
      WriteLog($"error:{exc.Message}\r\nstackTrace:{exc.StackTrace}", ConsoleColor.Red);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="msg"></param>
    private void OnError(string msg)
    {
      WriteLog($"error:{msg}", ConsoleColor.Red);
    }


    /// <summary>
    /// 响应接收到数据的消息并将数据传递到UI界面
    /// </summary>
    /// <param name="jsonData"></param>
    private void OnDataArrived(IDictionary jsonData)
    {
      var backgroundColor = jsonData.ToEnumValue<ConsoleColor>("BackgroundColor");
      var foregroundColor = jsonData.ToEnumValue<ConsoleColor>("ForegroundColor");
      var msg = jsonData.ToString("Msg");

      if (msg.IsNotNullOrEmpty())
      {
        WriteLog($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] {msg}", foregroundColor, backgroundColor);
      }
    }
  }
}
